const key = '怒发冲冠注,凭栏处、潇潇注雨歇.抬望眼、仰天长啸注,壮怀激烈.三十功名尘与土注,八千里路云和月注.莫等闲注、白了少年头,空悲切.靖康耻注,犹未雪.臣子恨,何时灭.驾长车,踏破贺兰山注缺.壮志饥餐胡虏肉,笑谈渴饮匈奴血.待从头、收拾旧山河,朝天阙' 
const {verify,sign} = require('jsonwebtoken')
const Whitelist= ['/user/login','/upload']
// token 鉴权中间件
const authMiddleware = async (ctx, next) => {  
	const token = ctx.request.header.token; // 假设 token 在 Authorization 头部中，格式为 'Bearer token' 
	const _d = new Date() 
	// console.log(ctx.url,'在'+new Date().toISOString().split('T')[0]+_d.getHours()+_d.getMinutes()+'时间被访问了','参数',ctx.request.body,'用户ID',ctx.state.user_id)
	// 跳过登录和注册路由的 token 校验  
	if (Whitelist.includes(ctx.url)||ctx.url.includes('/images')) {  
	  await next();  
	  return;  
	}  
	
	// 检查是否有 token  
	if (!token) {  
	  ctx.status = 200;  
	  ctx.body = {  
		code: 401,  
		msg: 'token没传'  
	  };  
	  return;  
	}  
	
	try {  
	  // 验证 token  
	  const decoded = verify(token, key); 
	  ctx.state.user_id = decoded.user_id
	  await next(); 
	} catch (err) {  
		console.log(err)
	  ctx.status = 200;  
	  ctx.body = {  
		code: 401,  
		msg: '身份信息已过期,请退出后重新登录'  
	  };  
	  return;
	}  
  };  
function generateToken(user_id){
	return sign(user_id,key,{algorithm:'HS256',expiresIn:"50h"})
}
module.exports = {
	generateToken,
	authMiddleware
}